package com.github.postsanf.yinian.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.flaviofaria.kenburnsview.KenBurnsView;
import com.flaviofaria.kenburnsview.RandomTransitionGenerator;
import com.flaviofaria.kenburnsview.Transition;
import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.CoverThemeAdapter;
import com.github.postsanf.yinian.adapter.HistoryCoverThemeAdapter;
import com.github.postsanf.yinian.adapter.PicRecyViewAdapter;
import com.github.postsanf.yinian.bean.CoverTheme;
import com.github.postsanf.yinian.bean.HistoryCoverTheme;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.entity.YNCoverThemeResponse;
import com.github.postsanf.yinian.entity.YNHisCoverThemeResponse;
import com.github.postsanf.yinian.service.ModifyTypeService;
import com.github.postsanf.yinian.service.UpLoadService;
import com.github.postsanf.yinian.utils.DateTimePickDialogUtil;
import com.github.postsanf.yinian.utils.ImageOptHelper;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.SizeFormat;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.WrapContentLinearLayoutManager;
import com.github.postsanf.yinian.view.DetailRecyclerView;
import com.github.postsanf.yinian.widget.RotateAnimation;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

public class TimeCardEditActivity extends BaseActivity implements View.OnClickListener, RotateAnimation.InterpolatedTimeListener {
    public static final String[] mouthlist = new String[]{"JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"};
    public static final int TAKE_MIC = 3;
    public static final int TAKE_SYNC = 4;
    private List<String> tempUris;
    private TextView timecarde_date_year;
    private TextView timecarde_date_mouth;
    private TextView timecarde_date_ri;
    private ImageView cursor;
    private int bmpw = 0; // 游标宽度
    private int offset = 0;// // 动画图片偏移量
    private int currIndex = 0;// 当前页卡编号
    private RelativeLayout reversal;
    private RelativeLayout cover;
    private RelativeLayout backcover;
    private boolean enableRefresh;
    private View clickView;// 当前的view
    private Animation animation = null;
    private RotateAnimation rotateAnim = null;
    private DetailRecyclerView dRecyclerView;
    private DetailRecyclerView historydRecyclerView;
    private CoverThemeAdapter ctAdapter;
    private List<CoverTheme> mCoverThemes = new ArrayList<>();
    private HistoryCoverThemeAdapter historyctAdapter;
    private List<HistoryCoverTheme> historyCoverThemes = new ArrayList<>();
    private SimpleDraweeView time_card_edit_cover_pic;
    private LinearLayout timecard_cover_sub;
    private LinearLayout timecard_elecment_sub;
    private LinearLayout timecard_pic_sub;
    private RecyclerView picRecylerView;
    private PicRecyViewAdapter picAdapter;
    private KenBurnsView time_card_edit_bg;
    private LinearLayout time_card_edit_from;
    private LinearLayout timecard_from_enty;
    private EditText et_write_from;
    private TextView tv_write_complete;
    private TextView tv_write_cancel;
    private ImageView timecard_mic_iv;
    private TextView timecard_mic_tx;
    private TextView timecard_from_content;
    private TextView timecard_cover_recommend;
    private TextView timecard_cover_history;
    private TextView timecard_cover_more;
    private InputMethodManager imm;
    private String coverUrl = "";
    private String micurl = "";
    private int miclenth = 0;
    private String editTime;
    private String editFrom;
    private long upstorge;
    private boolean IstoSync;
    private ConnectivityManager mConnectivityManager;
    private NetworkInfo netInfo;
    private ProgressDialog mProgressDialog;             // 进度条
    private int isPush = 0;
    private int aIsOfficial = 0;// 默认不是官方相册
    private String gimid;
    private int groupId;
    private SharedPreferences.Editor editor;
    private ImageView iv_time_card_edit_cover;
    private ImageView iv_time_card_edit_element;
    private ImageView iv_time_card_edit_pic;
    private String text_content = "";
    private int mictime;
    boolean mp3IsExist = false;
    private String edit;
    private boolean local = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        setContentView(R.layout.act_time_card_edit);
        registerBroadcastReceiver();
        initData();
        initCursorPos();
        initView();
        GetAllOfficialCovers();
    }

    private void initData() {
        edit = getIntent().getStringExtra("edit");
        if (edit != null && edit.equals("edit")) {
            SelectedImg.mSelectedImage.clear();
            SelectedImg.mSelectedImage.addAll(YNSingleton.getInstance().getCurStatus().getUrl());
        }
        tempUris = SelectedImg.mSelectedImage;
        groupId = YNSingleton.getInstance().getCurAlbum().getGroupid();
        gimid = YNSingleton.getInstance().getCurAlbum().getGimid();
        editor = getSharedPreferences(ACTIONs.mynetwork, 0).edit();
    }

    // 广播接收
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTIONs.actionUpdateCoverImg:
                    if (intent != null) {
                        coverUrl = intent.getStringExtra("url");
                        ImageOptHelper.showFrescoTodayshow(Uri.parse(coverUrl), time_card_edit_cover_pic, TimeCardEditActivity.this);
                    }
                    break;
                case ACTIONs.actionUpdateCoverBackImg:
                    updateCoverBackImg();
                    break;
                case ACTIONs.updataTimeCardEditPic:
                    Log.d("yuhao", "actionUpdateCoverBackImg");
                    tempUris = SelectedImg.mSelectedImage;
                    if (tempUris.size() != 0) {
                        updateImgs();
                    }
                    break;
                case ACTIONs.actionCloseAlbum:
                    finish();
                    break;
                case ACTIONs.actionMIcText:
                    mp3IsExist = intent.getBooleanExtra("isOK", false);
                    micurl = intent.getStringExtra("micUrl");
                    if (!StringUtils.isEmpty(micurl)) {
                        if (mp3IsExist) {
                            timecard_mic_tx.setText(MicActivity.timer + "“");
                            timecard_mic_iv.setImageResource(R.drawable.timecard_sound_yes);
                            micurl = intent.getStringExtra("micUrl");
                            miclenth = MicActivity.timer;
                        } else {
                            miclenth = 0;
                            timecard_mic_tx.setText("0'00'");
                            timecard_mic_iv.setImageResource(R.drawable.timecard_sound_no);
                        }
                    } else {
                        if (StringUtils.isEmpty(intent.getStringExtra("micpath"))) {
                            miclenth = 0;
                            timecard_mic_tx.setText("0'00'");
                            timecard_mic_iv.setImageResource(R.drawable.timecard_sound_no);
                        } else {
                            String url = intent.getStringExtra("micpath");
                            Log.i("xjs", "url22222===>" + url);
                            String newurl = url.substring(url.lastIndexOf("com") + 4, url.indexOf("mp3") + 3);
                            Log.i("xjs", "newurl22222===>" + newurl);
                            micurl = newurl;
                        }
                    }

                    break;
                case ACTIONs.actionUpdateFromText:
                    if (intent != null) {
                        String fromtx = intent.getStringExtra("tx");
                        text_content = fromtx;
                        timecard_from_content.setTextColor(getResources().getColor(R.color.timecard_from_txcolor_drak));
                        timecard_from_content.setText(fromtx);
                    }
                    break;
            }
        }
    };

    private void updateImgs() {
        picAdapter.notifyDataSetChanged();
        updateCoverBackImg();
    }

    //注册广播
    private void registerBroadcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.updataTimeCardEditPic);
        myIntentFilter.addAction(ACTIONs.actionUpdateCoverImg);
        myIntentFilter.addAction(ACTIONs.actionUpdateCoverBackImg);
        myIntentFilter.addAction(ACTIONs.actionUpdateFromText);
        myIntentFilter.addAction(ACTIONs.actionCloseAlbum);
        myIntentFilter.addAction(ACTIONs.actionMIcText);
        this.registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    private void initView() {
        IstoSync = getIntent().getBooleanExtra(ACTIONs.IstoSync, false);
        findViewById(R.id.time_card_edit_back).setOnClickListener(this);
        findViewById(R.id.timecard_upload).setOnClickListener(this);
        findViewById(R.id.time_card_mic).setOnClickListener(this);
        findViewById(R.id.time_card_edit_time).setOnClickListener(this);
        findViewById(R.id.time_card_edit_cover).setOnClickListener(this);
        findViewById(R.id.time_card_edit_element).setOnClickListener(this);
        findViewById(R.id.time_card_edit_pic).setOnClickListener(this);
        timecarde_date_year = (TextView) findViewById(R.id.timecarde_date_year);
        timecarde_date_mouth = (TextView) findViewById(R.id.timecarde_date_mouth);
        timecarde_date_ri = (TextView) findViewById(R.id.timecarde_date_ri);
        iv_time_card_edit_cover = ((ImageView) findViewById(R.id.iv_time_card_edit_cover));
        iv_time_card_edit_element = ((ImageView) findViewById(R.id.iv_time_card_edit_element));
        iv_time_card_edit_pic = ((ImageView) findViewById(R.id.iv_time_card_edit_pic));

        Date mdate = new Date(System.currentTimeMillis());
        String str = new SimpleDateFormat("yyyy-MM-dd").format(mdate);
        timecarde_date_year.setText(str.split("-")[0]);
        timecarde_date_mouth.setText(mouthlist[mdate.getMonth()]);
        timecarde_date_ri.setText("·" + str.split("-")[2] + "·");
        timecarde_date_year.setTag(str);
        time_card_edit_from = (LinearLayout) findViewById(R.id.time_card_edit_from);
        time_card_edit_from.setOnClickListener(this);
        timecard_from_enty = (LinearLayout) findViewById(R.id.timecard_from_enty);
        et_write_from = (EditText) findViewById(R.id.et_write_from);
        tv_write_complete = (TextView) findViewById(R.id.tv_write_complete);
        tv_write_cancel = (TextView) findViewById(R.id.tv_write_cancel);
        tv_write_complete.setOnClickListener(this);
        tv_write_cancel.setOnClickListener(this);
        reversal = (RelativeLayout) findViewById(R.id.time_card_reversal);
        reversal.setOnClickListener(this);
        cover = (RelativeLayout) findViewById(R.id.time_card_reversal_cover);
        backcover = (RelativeLayout) findViewById(R.id.time_card_reversal_back);
        timecard_mic_iv = (ImageView) findViewById(R.id.timecard_mic_iv);
        timecard_mic_tx = (TextView) findViewById(R.id.timecard_mic_tx);
        timecard_from_content = (TextView) findViewById(R.id.timecard_from_content);
        time_card_edit_bg = (KenBurnsView) findViewById(R.id.time_card_edit_bg);
        time_card_edit_bg.setTransitionGenerator(new RandomTransitionGenerator(3000, new LinearInterpolator()));
        timecard_cover_sub = (LinearLayout) findViewById(R.id.timecard_cover_sub);
        timecard_elecment_sub = (LinearLayout) findViewById(R.id.timecard_elecment_sub);
        timecard_cover_recommend = (TextView) findViewById(R.id.timecard_cover_recommend);
        timecard_cover_history = (TextView) findViewById(R.id.timecard_cover_history);
        timecard_cover_more = (TextView) findViewById(R.id.timecard_cover_more);
        timecard_cover_recommend.setOnClickListener(this);
        timecard_cover_history.setOnClickListener(this);
        timecard_cover_more.setOnClickListener(this);
        findViewById(R.id.timecard_from_enty_scroll).setOnClickListener(this);
        time_card_edit_cover_pic = (SimpleDraweeView) findViewById(R.id.time_card_edit_cover_pic);
        dRecyclerView = (DetailRecyclerView) findViewById(R.id.cover_detail_horizontal);
        WrapContentLinearLayoutManager horLayoutManager = new WrapContentLinearLayoutManager(this);
        horLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        dRecyclerView.setLayoutManager(horLayoutManager);
        ctAdapter = new CoverThemeAdapter(this, mCoverThemes);
        dRecyclerView.setHasFixedSize(true);
        dRecyclerView.setAdapter(ctAdapter);
        ctAdapter.setOnItemClickLitener(new CoverThemeAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                coverUrl = mCoverThemes.get(position).getOfficialCoverPicture();
                ImageOptHelper.showFrescoTodayshow(Uri.parse(coverUrl), time_card_edit_cover_pic, TimeCardEditActivity.this);
            }
        });
        historydRecyclerView = (DetailRecyclerView) findViewById(R.id.cover_hisdetail_horizontal);
        WrapContentLinearLayoutManager hishorLayoutManager = new WrapContentLinearLayoutManager(this);
        hishorLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        historydRecyclerView.setLayoutManager(hishorLayoutManager);
        historyctAdapter = new HistoryCoverThemeAdapter(this, historyCoverThemes);
        historydRecyclerView.setHasFixedSize(true);
        historydRecyclerView.setAdapter(historyctAdapter);
        historyctAdapter.setOnItemClickLitener(new HistoryCoverThemeAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                coverUrl = historyCoverThemes.get(position).getHistoryCoverPicture();
                ImageOptHelper.showFrescoTodayshow(Uri.parse(coverUrl), time_card_edit_cover_pic, TimeCardEditActivity.this);
            }
        });
        timecard_pic_sub = (LinearLayout) findViewById(R.id.timecard_pic_sub);
        picRecylerView = (RecyclerView) findViewById(R.id.timecard_pic_sub_recy);
        WrapContentLinearLayoutManager horLayoutManager2 = new WrapContentLinearLayoutManager(this);
        horLayoutManager2.setOrientation(LinearLayoutManager.HORIZONTAL);
        picRecylerView.setLayoutManager(horLayoutManager2);
        picAdapter = new PicRecyViewAdapter(this, tempUris);
        picRecylerView.setHasFixedSize(true);
        picRecylerView.setAdapter(picAdapter);
        if (edit != null && edit.equals("edit")) {
            timecard_from_content.setText(YNSingleton.getInstance().getCurStatus().getEplace());
            String strtime = YNSingleton.getInstance().getCurStatus().getEmemorytime().split(" ")[0];
            timecarde_date_year.setText(strtime.split("-")[0]);
            timecarde_date_year.setTag(strtime);
            try {
                DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
                Date date = fmt.parse(YNSingleton.getInstance().getCurStatus().getEmemorytime());
                timecarde_date_mouth.setText(mouthlist[date.getMonth()]);
            } catch (Exception e) {
                e.printStackTrace();
            }
            timecarde_date_ri.setText("·" + strtime.split("-")[2] + "·");
            coverUrl = YNSingleton.getInstance().getCurStatus().getEcover();
            ImageOptHelper.showFrescoTodayshow(Uri.parse(coverUrl), time_card_edit_cover_pic, TimeCardEditActivity.this);
            if (!StringUtils.isEmpty(YNSingleton.getInstance().getCurStatus().getEaudio())) {
                MainActivity.micpath = YNSingleton.getInstance().getCurStatus().getEaudio();
                mp3IsExist = true;
                mictime = getIntent().getIntExtra("mictime", 0);
                timecard_mic_tx.setText(mictime + "“");
                String url = YNSingleton.getInstance().getCurStatus().getEaudio();
                micurl = url.substring(url.lastIndexOf("com") + 4, url.indexOf("mp3") + 3);
                Log.i("xjs", "uuurlmm=====>" + micurl);
            }
        }
        updateCoverBackImg();
    }

    int start = 0;

    private void updateCoverBackImg() {
        start = 0;
        if (SelectedImg.mSelectedImage.size() >= 0) {
            if (SelectedImg.mSelectedImage.size() == 1) {
                if (SelectedImg.mSelectedImage.get(0).startsWith("http")) {
                    ImageLoader.getInstance().displayImage(SelectedImg.mSelectedImage.get(0), time_card_edit_bg);
                } else {
                    ImageLoader.getInstance().displayImage("file://" + SelectedImg.mSelectedImage.get(0), time_card_edit_bg);
                }
            } else {
                if (SelectedImg.mSelectedImage.get(0).startsWith("http")) {
                    ImageLoader.getInstance().displayImage(SelectedImg.mSelectedImage.get(0), time_card_edit_bg);
                } else {
                    ImageLoader.getInstance().displayImage("file://" + SelectedImg.mSelectedImage.get(0), time_card_edit_bg);
                }
                time_card_edit_bg.setTransitionListener(transitionListener);
            }
        }
    }


    KenBurnsView.TransitionListener transitionListener = new KenBurnsView.TransitionListener() {

        @Override
        public void onTransitionStart(Transition transition) {
        }

        @Override
        public void onTransitionEnd(Transition transition) {
            start++;
            if (start == SelectedImg.mSelectedImage.size()) {
                start = 0;
            }
            if (start <= SelectedImg.mSelectedImage.size() - 1) {
                if (SelectedImg.mSelectedImage.get(start).startsWith("http")) {
                    ImageLoader.getInstance().displayImage(SelectedImg.mSelectedImage.get(start), time_card_edit_bg);
                } else {
                    ImageLoader.getInstance().displayImage("file://" + SelectedImg.mSelectedImage.get(start), time_card_edit_bg);
                }
            }
        }
    };

    //初始化指示器位置
    public void initCursorPos() {
        cursor = (ImageView) findViewById(R.id.cursor);
        bmpw = BitmapFactory.decodeResource(getResources(), R.drawable.time_postcard_bar)
                .getWidth();// 获取图片宽度
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenW = dm.widthPixels;// 获取分辨率宽度
        offset = (screenW / 3 - bmpw) / 2;// 计算偏移量
        Matrix matrix = new Matrix();
        matrix.postTranslate(offset, 0);
        cursor.setImageMatrix(matrix);// 设置动画初始位置
        int one = offset * 2 + bmpw;
        animation = new TranslateAnimation(offset, one, 0, 0);
        animation.setFillAfter(true);
        animation.setDuration(300);
        cursor.startAnimation(animation);
        currIndex = 1;
    }


    @Override
    public void interpolatedTime(float interpolatedTime) {
        if (enableRefresh && interpolatedTime > 0.5f) {
            setHint();
            enableRefresh = false;
        }
    }


    public void setHint() {
        if (clickView == backcover) {
            cover.setVisibility(View.GONE);
            backcover.setVisibility(View.VISIBLE);
        } else if (clickView == cover) {
            backcover.setVisibility(View.GONE);
            cover.setVisibility(View.VISIBLE);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        SelectedImg.mSelectedImage.clear();
        MicActivity.mMp3FileName = "";
        this.unregisterReceiver(mBroadcastReceiver);
    }


    @Override
    public void onClick(View view) {
        float cX = reversal.getWidth() / 2.0f;
        float cY = reversal.getHeight() / 2.0f;
        int one = offset * 2 + bmpw;// 页卡1 -> 页卡2 偏移量
        int two = one * 2;// 页卡1 -
        switch (view.getId()) {
            case R.id.time_card_edit_back:
                new AlertDialog.Builder(TimeCardEditActivity.this).setMessage("确定不要这张语音图集了吗？")
                        .setPositiveButton(R.string.yn_app_ok, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                finish();
                            }
                        }).setNegativeButton(R.string.yn_app_cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    }
                }).show();
                break;
            case R.id.timecard_upload:
                Log.i("xjs", "timecard_upload");
                Log.i("xjs", "timecard_coverUrl==>" + coverUrl);
                if (tempUris.size() == 0) {
                    Toast.makeText(TimeCardEditActivity.this, "选择图片上传", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (StringUtils.isEmpty(coverUrl)) {
                    Toast.makeText(TimeCardEditActivity.this, "选择封面后上传", Toast.LENGTH_SHORT).show();
                    return;
                }
                editTime = timecarde_date_year.getTag().toString();
                editFrom = timecard_from_content.getText().toString();
                //是否同步
                long totalSize = 0;
                for (int i = 0; i < SelectedImg.mSelectedImage.size(); i++) {
                    String address = SelectedImg.mSelectedImage.get(i);
                    if (!address.startsWith("http")) {
                        File uploadImg = new File(address);
                        long imgSize = uploadImg.length();
                        totalSize += imgSize;
                        local = true;
                    }
                }
                upstorge = totalSize;
                String fsize = SizeFormat.formatSize(totalSize);
                if (!IstoSync) {
                    mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                    netInfo = mConnectivityManager.getActiveNetworkInfo();
                    if (netInfo != null && netInfo.isAvailable()) {
                        if (netInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                            if (edit != null && edit.equals("edit")) {
                                moidfyUpload(false);
                            } else {
                                doUpImg(false);
                            }
                        } else if (netInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                            int netfrist = getSharedPreferences(ACTIONs.mynetwork, 0).getInt(ACTIONs.networkFrist, 0);
                            String nettype = getSharedPreferences(ACTIONs.mynetwork, 0).getString(ACTIONs.networkType, "");
                            if (!nettype.equals("") && nettype.equals(ACTIONs.network3GWIFI)) {
                                if (edit != null && edit.equals("edit")) {
                                    moidfyUpload(false);
                                } else {
                                    doUpImg(false);
                                }
                            } else {
                                if (netfrist == 0) {
                                    FristNetWork(fsize);
                                    editor.putInt(ACTIONs.networkFrist, 1);
                                    editor.commit();
                                } else {
                                    SecondNetWork(fsize);
                                }
                            }
                        }
                    }
                } else {
                    syncUpImg(false);
                }
                String gtype = YNSingleton.getInstance().getCurAlbum().getGtype();
                if (gtype != null && gtype.equals("6") || gtype.equals("7") || gtype.equals("8")) {
                    startService(new Intent(TimeCardEditActivity.this, ModifyTypeService.class));
                }
//                SelectedImg.mSelectedImage.clear();
                break;
            case R.id.time_card_mic:
                Intent micIntent = new Intent(TimeCardEditActivity.this, MicActivity.class);
                micIntent.putExtra("mp3IsExist", mp3IsExist);
                micIntent.putExtra("micpath", MainActivity.micpath);
                micIntent.putExtra("mictime", mictime);
                startActivityForResult(micIntent, TAKE_MIC);
                break;
            case R.id.time_card_edit_time:
                DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(this, timecarde_date_year.getTag().toString());
                dateTimePicKDialog.dateTimePicTimeCardDialog(timecarde_date_year, timecarde_date_mouth, timecarde_date_ri);
                break;
            case R.id.time_card_edit_from:
                Intent intent = new Intent(TimeCardEditActivity.this, TimeCardFromActivity.class);
                intent.putExtra("text_content", text_content);
                startActivity(intent);
                break;
//            case R.id.tv_write_complete:
//                timecard_from_content.setTextColor(getResources().getColor(R.color.timecard_from_txcolor_drak));
//                timecard_from_content.setText(et_write_from.getText().toString());
//                et_write_from.setText("");
//                imm.hideSoftInputFromWindow(et_write_from.getWindowToken(), 0);
//                timecard_from_enty.setVisibility(View.GONE);
//                break;
//            case R.id.tv_write_cancel:
//                imm.hideSoftInputFromWindow(et_write_from.getWindowToken(), 0);
//                timecard_from_enty.setVisibility(View.GONE);
//                break;
//            case R.id.timecard_from_enty_scroll:
//                imm.hideSoftInputFromWindow(et_write_from.getWindowToken(), 0);
//                timecard_from_enty.setVisibility(View.GONE);
//                break;
            case R.id.timecard_cover_recommend:
                historydRecyclerView.setVisibility(View.GONE);
                dRecyclerView.setVisibility(View.VISIBLE);
                timecard_cover_recommend.setTextColor(getResources().getColor(R.color.timecard_cover_tip_drak));
                timecard_cover_history.setTextColor(getResources().getColor(R.color.timecard_cover_tip_light));
                timecard_cover_more.setTextColor(getResources().getColor(R.color.timecard_cover_tip_light));
                GetAllOfficialCovers();
                break;
            case R.id.timecard_cover_history:
                dRecyclerView.setVisibility(View.GONE);
                historydRecyclerView.setVisibility(View.VISIBLE);
                timecard_cover_history.setTextColor(getResources().getColor(R.color.timecard_cover_tip_drak));
                timecard_cover_recommend.setTextColor(getResources().getColor(R.color.timecard_cover_tip_light));
                timecard_cover_more.setTextColor(getResources().getColor(R.color.timecard_cover_tip_light));
                GetUserHistoryCovers();
                break;
            case R.id.timecard_cover_more:
                timecard_cover_more.setTextColor(getResources().getColor(R.color.timecard_cover_tip_drak));
                timecard_cover_history.setTextColor(getResources().getColor(R.color.timecard_cover_tip_light));
                timecard_cover_recommend.setTextColor(getResources().getColor(R.color.timecard_cover_tip_light));
                startActivity(new Intent(TimeCardEditActivity.this, TimeCardCoverMore.class));
                break;
            case R.id.time_card_edit_cover:
                iv_time_card_edit_cover.setImageResource(R.drawable.time_card_edit_cover_select);
                iv_time_card_edit_element.setImageResource(R.drawable.time_card_edit_element);
                iv_time_card_edit_pic.setImageResource(R.drawable.time_card_edit_pic);
                enableRefresh = true;
                clickView = cover;
                rotateAnim = new RotateAnimation(cX, cY, RotateAnimation.ROTATE_INCREASE);
                if (rotateAnim != null && currIndex == 1 || currIndex == 2) {
                    rotateAnim.setInterpolatedTimeListener(TimeCardEditActivity.this);
                    rotateAnim.setFillAfter(true);
                    reversal.startAnimation(rotateAnim);
                }
                timecard_elecment_sub.setVisibility(View.GONE);
                timecard_pic_sub.setVisibility(View.GONE);
                timecard_cover_sub.setVisibility(View.VISIBLE);
                if (currIndex == 1) {
                    animation = new TranslateAnimation(one, 0, 0, 0);
                } else if (currIndex == 2) {
                    animation = new TranslateAnimation(two, 0, 0, 0);
                }
                animation.setFillAfter(true);
                animation.setDuration(300);
                cursor.startAnimation(animation);
                currIndex = 0;
                break;
            case R.id.time_card_edit_element:
                iv_time_card_edit_cover.setImageResource(R.drawable.time_card_edit_cover);
                iv_time_card_edit_element.setImageResource(R.drawable.time_card_edit_element_select);
                iv_time_card_edit_pic.setImageResource(R.drawable.time_card_edit_pic);
                enableRefresh = true;
                clickView = backcover;
                rotateAnim = new RotateAnimation(cX, cY, RotateAnimation.ROTATE_DECREASE);
                if (rotateAnim != null && currIndex == 0) {
                    rotateAnim.setInterpolatedTimeListener(TimeCardEditActivity.this);
                    rotateAnim.setFillAfter(true);
                    reversal.startAnimation(rotateAnim);
                }
                timecard_cover_sub.setVisibility(View.GONE);
                timecard_pic_sub.setVisibility(View.GONE);
                timecard_elecment_sub.setVisibility(View.VISIBLE);
                if (currIndex == 0) {
                    animation = new TranslateAnimation(offset, one, 0, 0);
                } else if (currIndex == 2) {
                    animation = new TranslateAnimation(two, one, 0, 0);
                }
                animation.setFillAfter(true);
                animation.setDuration(300);
                cursor.startAnimation(animation);
                currIndex = 1;
                break;
            case R.id.time_card_edit_pic:
                iv_time_card_edit_cover.setImageResource(R.drawable.time_card_edit_cover);
                iv_time_card_edit_element.setImageResource(R.drawable.time_card_edit_element);
                iv_time_card_edit_pic.setImageResource(R.drawable.time_card_edit_pic_select);
                enableRefresh = true;
                clickView = backcover;
                rotateAnim = new RotateAnimation(cX, cY, RotateAnimation.ROTATE_DECREASE);
                if (rotateAnim != null && currIndex == 0) {
                    rotateAnim.setInterpolatedTimeListener(TimeCardEditActivity.this);
                    rotateAnim.setFillAfter(true);
                    reversal.startAnimation(rotateAnim);
                }
                timecard_cover_sub.setVisibility(View.GONE);
                timecard_elecment_sub.setVisibility(View.GONE);
                timecard_pic_sub.setVisibility(View.VISIBLE);
                if (currIndex == 0) {
                    animation = new TranslateAnimation(offset, two, 0, 0);
                } else if (currIndex == 1) {
                    animation = new TranslateAnimation(one, two, 0, 0);
                }
                animation.setFillAfter(true);
                animation.setDuration(300);
                cursor.startAnimation(animation);
                currIndex = 2;
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_MIC:
                if (data != null) {
                    micurl = data.getStringExtra("micUrl");
                    if (!StringUtils.isEmpty(micurl)) {
                        mp3IsExist = data.getBooleanExtra("isOK", false);
                        if (mp3IsExist) {
                            timecard_mic_tx.setText(MicActivity.timer + "“");
                            timecard_mic_iv.setImageResource(R.drawable.timecard_sound_yes);
                            miclenth = MicActivity.timer;
                            micurl = data.getStringExtra("micUrl");
                        } else {
                            miclenth = 0;
                            timecard_mic_tx.setText("0'00'");
                            timecard_mic_iv.setImageResource(R.drawable.timecard_sound_no);
                        }
                    } else {
                        if (StringUtils.isEmpty(data.getStringExtra("micpath"))) {
                            miclenth = 0;
                            timecard_mic_tx.setText("0'00'");
                            timecard_mic_iv.setImageResource(R.drawable.timecard_sound_no);
                        } else {
                            String url = data.getStringExtra("micpath");
                            Log.i("xjs", "url22222===>" + url);
                            String newurl = url.substring(url.lastIndexOf("com") + 4, url.indexOf("mp3") + 3);
                            Log.i("xjs", "newurl22222===>" + newurl);
                            micurl = newurl;
                        }
                    }
                }
                break;
            case TAKE_SYNC:
                if (data != null) {
                    finish();
                }
                break;
        }
    }

    private void doUpImg(boolean isPause) {
        mProgressDialog = ProgressDialog.show(this, "", CommonConstants.TIP_LOAD_UP);
        Intent mIntent = new Intent(this, UpLoadService.class);
        mIntent.setAction(ACTIONs.actionPublishPhoto);
        mIntent.putExtra(ACTIONs.aUid, application.getCurID() + "");
        mIntent.putExtra(ACTIONs.aGid, groupId + "");
        mIntent.putExtra(ACTIONs.aGimid, gimid);
        mIntent.putExtra(ACTIONs.aType, StringUtils.isOfficialGroup(YNSingleton.getInstance().getCurAlbum().getGtype()) ? 1 : 0);
        mIntent.putExtra(ACTIONs.aPush, isPush);
        mIntent.putExtra(ACTIONs.aIsOfficial, aIsOfficial);
        mIntent.putExtra(ACTIONs.aGname, YNSingleton.getInstance().getCurAlbum().getGname());
        mIntent.putExtra(ACTIONs.aContent, "");
        mIntent.putExtra(ACTIONs.aisPause, isPause);
        mIntent.putExtra(ACTIONs.upstorage, SizeFormat.formatDouble(upstorge, SizeFormat.FZ_KB));
        mIntent.putExtra(ACTIONs.upismemorycard, 2);
        mIntent.putExtra(ACTIONs.uptags, "");
        mIntent.putExtra(ACTIONs.upaudio, micurl);
        mIntent.putExtra(ACTIONs.upmemorytime, editTime);
        mIntent.putExtra(ACTIONs.upplace, editFrom);
        mIntent.putExtra(ACTIONs.upaudiotime, String.valueOf(miclenth));
        mIntent.putExtra(ACTIONs.upcoverUrl, coverUrl);
        startService(mIntent);
        startActivity(new Intent(this, UpLoadActivity.class).putExtra(ACTIONs.IstoSetWifi, isPause));
        Intent upIntent = new Intent(ACTIONs.actionCloseAlbum);
        upIntent.putExtra(ACTIONs.aIsClearSelect, 1);
        sendBroadcast(upIntent);
        mProgressDialog.dismiss();
    }

    private void syncUpImg(boolean isPause) {
        Intent syncIntent = new Intent(TimeCardEditActivity.this, CardSyncUploadActivity.class);
        syncIntent.putExtra(ACTIONs.aUid, application.getCurID() + "");
        syncIntent.putExtra(ACTIONs.aGid, groupId + "");
        syncIntent.putExtra(ACTIONs.aType, StringUtils.isOfficialGroup(YNSingleton.getInstance().getCurAlbum().getGtype()) ? 1 : 0);
        syncIntent.putExtra(ACTIONs.aPush, isPush);
        syncIntent.putExtra(ACTIONs.aIsOfficial, aIsOfficial);
        syncIntent.putExtra(ACTIONs.aGname, YNSingleton.getInstance().getCurAlbum().getGname());
        syncIntent.putExtra(ACTIONs.aContent, "");
        syncIntent.putExtra(ACTIONs.aisPause, isPause);
        syncIntent.putExtra(ACTIONs.upstorage, String.valueOf(SizeFormat.formatDouble(upstorge, SizeFormat.FZ_KB)));
        syncIntent.putExtra(ACTIONs.upismemorycard, 2);
        syncIntent.putExtra(ACTIONs.uptags, "");
        syncIntent.putExtra(ACTIONs.upaudio, micurl);
        syncIntent.putExtra(ACTIONs.upmemorytime, editTime);
        syncIntent.putExtra(ACTIONs.upplace, editFrom);
        syncIntent.putExtra(ACTIONs.upaudiotime, String.valueOf(miclenth));
        syncIntent.putExtra(ACTIONs.upcoverUrl, coverUrl);
        startActivityForResult(syncIntent, TAKE_SYNC);
    }

    private void GetAllOfficialCovers() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.GetRecommendCover))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNCoverThemeResponse resAlertBg = gson.fromJson(s, YNCoverThemeResponse.class);
                        if (ReqUtils.isSuccess(resAlertBg.getCode())) {
                            List<CoverTheme> YNTaglist = resAlertBg.getData();
                            mCoverThemes.clear();
                            mCoverThemes.addAll(YNTaglist);
                            ctAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void GetUserHistoryCovers() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.GetUserHistoryCovers))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNHisCoverThemeResponse resAlertBg = gson.fromJson(s, YNHisCoverThemeResponse.class);
                        if (ReqUtils.isSuccess(resAlertBg.getCode())) {
                            List<HistoryCoverTheme> YNTaglist = resAlertBg.getData();
                            if (YNTaglist.size() > 0) {
                                historyCoverThemes.clear();
                                historyCoverThemes.addAll(YNTaglist);
                                historyctAdapter.notifyDataSetChanged();
                            } else {
                                showToast("暂无历史！");
                            }

                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    // 总长度
    private long getTotalLenth() {
        long totalSize = 0;
        for (int i = 0; i < SelectedImg.mSelectedImage.size(); i++) {
            String address = SelectedImg.mSelectedImage.get(i);
            File uploadImg = new File(address);
            long imgSize = uploadImg.length();
            totalSize += imgSize;
        }
        return totalSize;
    }

    public void SecondNetWork(String fsize) {
        final AlertDialog dlg = new AlertDialog.Builder(this).create();
        dlg.show();
        Window window = dlg.getWindow();
        window.setContentView(R.layout.publish_network_dialog);
        TextView tt = (TextView) window.findViewById(R.id.pp_title);
        tt.setText(">_< 您关闭了使用流量上传开关，你在使用3g/4g网络环境下，这会消耗您" + fsize + "流量，确定继续上传吗？");
        final TextView ok = (TextView) window.findViewById(R.id.btn_ep_ok);
        ok.setText("取消");
        ok.setBackgroundColor(getResources().getColor(R.color.white));
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dlg.cancel();
            }
        });
        final TextView cancel = (TextView) window
                .findViewById(R.id.btn_ep_cancel);
        cancel.setText("仅一次");
        cancel.setBackgroundColor(getResources().getColor(R.color.white));
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (edit != null && edit.equals("edit")) {
                    moidfyUpload(false);
                } else {
                    doUpImg(false);
                }
                dlg.cancel();
            }
        });
    }

    public void FristNetWork(String fsize) {
        final AlertDialog dlg = new AlertDialog.Builder(this).create();
        dlg.show();
        Window window = dlg.getWindow();
        window.setContentView(R.layout.publish_network_dialog);
        TextView tt = (TextView) window.findViewById(R.id.pp_title);
        tt.setText("您现在处于移动网络环境下，将消耗" + fsize + "流量，是否使用流量继续上传?");
        final TextView ok = (TextView) window.findViewById(R.id.btn_ep_ok);
        ok.setText("不允许");
        ok.setBackgroundColor(getResources().getColor(R.color.white));
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (edit != null && edit.equals("edit")) {
                    moidfyUpload(true);
                } else {
                    doUpImg(true);
                }
                dlg.cancel();
            }
        });
        final TextView cancel = (TextView) window
                .findViewById(R.id.btn_ep_cancel);
        cancel.setText("确定");
        cancel.setBackgroundColor(getResources().getColor(R.color.white));
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                editor.putString(ACTIONs.networkType, ACTIONs.network3GWIFI);
                editor.commit();
                if (edit != null && edit.equals("edit")) {
                    moidfyUpload(true);
                } else {
                    doUpImg(true);
                }
                dlg.cancel();
            }
        });
    }


    private void moidfyUpload(boolean isPause) {
        mProgressDialog = ProgressDialog.show(this, "", CommonConstants.TIP_LOAD_UP);
        Intent mIntent = new Intent(this, UpLoadService.class);
        mIntent.setAction(ACTIONs.modifyStatus);
        mIntent.putExtra(ACTIONs.aUid, application.getCurID() + "");
        mIntent.putExtra(ACTIONs.aGid, groupId + "");
        mIntent.putExtra(ACTIONs.aGimid, gimid);
        mIntent.putExtra(ACTIONs.aEid, YNSingleton.getInstance().getCurStatus().getEid() + "");
        mIntent.putExtra(ACTIONs.aContent, "");
        mIntent.putExtra(ACTIONs.aEplace, timecard_from_content.getText().toString());
        mIntent.putExtra(ACTIONs.upmemorytime, editTime);
        mIntent.putExtra(ACTIONs.upaudio, micurl);
        mIntent.putExtra(ACTIONs.upcoverUrl, coverUrl);
        mIntent.putExtra(ACTIONs.uptags, "");
        mIntent.putExtra(ACTIONs.upgname, YNSingleton.getInstance().getCurAlbum().getGname());
        mIntent.putExtra(ACTIONs.aType, StringUtils.isOfficialGroup(YNSingleton.getInstance().getCurAlbum().getGtype()) ? 1 : 0);
//        mIntent.putExtra(ACTIONs.aPush, isPush);
        if (local) {
            mIntent.putExtra(ACTIONs.upstorage, SizeFormat.formatDouble(upstorge, SizeFormat.FZ_KB));
        } else {
            mIntent.putExtra(ACTIONs.upstorage, YNSingleton.getInstance().getCurStatus().geteStoragePlace());
        }
        mIntent.putExtra(ACTIONs.picType, "postCard");
        mIntent.putExtra(ACTIONs.aisPause, isPause);
        startService(mIntent);

        startActivity(new Intent(this, UpLoadActivity.class).putExtra(ACTIONs.IstoSetWifi, isPause));
        Intent upIntent = new Intent(ACTIONs.actionCloseAlbum);
        upIntent.putExtra(ACTIONs.aIsClearSelect, 1);
        sendBroadcast(upIntent);
        mProgressDialog.dismiss();
    }

    private long fristTime;

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
        fristTime = System.currentTimeMillis();
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
        Intent intent = new Intent(ACTIONs.record);
        intent.putExtra("key", "timePostcard_3");
        intent.putExtra("value", new Long(System.currentTimeMillis() - fristTime).intValue());
        sendBroadcast(intent);
    }

}
